import { useEffect, useRef, useState } from 'react'
import Taro, { FC, useDidShow, useRouter } from '@tarojs/taro'
import { EMPTY, firstValueFrom, Subject, Subscription } from 'rxjs'
import { catchError, debounceTime, map, switchMap, tap } from 'rxjs/operators'
import { View, Text, Image } from '@tarojs/components'
import { AtList, AtListItem, AtInput, AtForm, AtIcon, AtTextarea, AtRadio } from "taro-ui"
import "taro-ui/dist/style/components/button.scss" // 按需引入
import "taro-ui/dist/style/components/radio.scss";
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/image-picker.scss";

import { uploadFile, vodUploader } from '@/utils/qcloudHelpers'
import { useRoomDataFacade } from '@/hooks/useRoomDataFacade'
import { getLogger } from '@/utils/log'
import { onEmit } from '@/utils/rxHelpers'
import { formatTime, getObjDiff, isObjEmpty, isPromise } from '@/utils'
import { ROOMSTATS_TYPE } from '@/constants/room'
import { EditRoomParams } from '@/models/request/roomReq'
import { useAuthFacade } from '@/hooks/useAuthFacade'
import { APPROVE_STATUS } from '@/constants/user'

import DateTimePicker from '@/components/DateTimePicker/index';
import './index.scss'

export const EditLive: FC = () => {
  const logger = getLogger("/pages/liveRoom/editLive");

  const router = useRouter();
  const roomId = router.params.roomId || "";

  //用不到的变量不用写
  //FIXME 这个导入太长容易犯错
  const [roomFacade] = useRoomDataFacade();
  const [authFacade, , , , , , userApprovalStatus,] = useAuthFacade()

  const initSubject = () => new Subject<any>();

  // 初始化按钮接收参数subject，所有按钮或者操作都可以通过这个emmiter触发
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject);

  //时间选择器开始和结束时间
  const curTime = new Date().getTime()
  const startTimeHolder = curTime + 1 * 3600 * 1000;
  const endTimeHolder = startTimeHolder + 8 * 3600 * 1000

  //从直播间传过来的原有数据
  const oldParams = useRef({} as EditRoomParams);

  const [roomName, setRoomName] = useState('')
  const [ownerName, setOwnerName] = useState('')
  const [description, setDescription] = useState('')
  const [serve, setServe] = useState(true)
  const [select, setSelect] = useState(0)
  const [watch, setWatch] = useState(true)
  const [picUrl, setPicUrl] = useState("https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/default.png")
  const [preLoadVideo, setPreLoadVideo] = useState("")
  const [videoUploader, setVideoUploader] = useState(null);
  const [coverFile, setCoverFile] = useState("") //暖场视频
  const [pauseFile, setPauseFile] = useState("") //过场视频
  const [startTime, setStartTime] = useState(startTimeHolder)
  const [endTime, setEndTime] = useState(endTimeHolder)
  const [isEdit, setIsEdit] = useState(false)
  // const [changeEndTime, setChangeEndTime] = useState(endTimeValue)
  const [coverFileUrl, setCoverFileUrl] = useState({
    tempFilePaths: [""],
    tempFiles: [{
      path: "",
      size: 0
    }],
    errMsg: ""
  })
  const handleChange1 = (value) => {
    setRoomName(value)
  }
  const handleChange2 = (value) => {
    setOwnerName(value)
  }
  const handleChange4 = (value) => {
    setDescription(value)
  }

  //开始时间
  const pickStart = (value) => {
    //兼容安卓和iOS，否则iOS的日期显示有问题
    const time = value.current.replace(/-/g, '/');

    const start = new Date(time).getTime();
    setStartTime(start);
    const newEndTiemV = start + 8 * 3600 * 1000
    setEndTime(newEndTiemV);
  }

  //结束时间
  const pickEnd = (value) => {
    const time = value.current.replace(/-/g, '/');

    const end = new Date(time).getTime();
    if (0 < end - startTime && end - startTime < 8 * 3600 * 1000) {
      setEndTime(end)
    } else {
      Taro.showToast({
        title: '结束时间不能大于8小时或小于开始时间',
        icon: 'none',
        duration: 2000
      })
      setEndTime(startTime + 8 * 3600 * 1000)
    }
  }

  const handleChangeServe = (value) => {
    setServe(value)
  }
  const handleChange5 = (value) => {
    setSelect(value)
  }
  const handleChange6 = (value) => {
    setWatch(value)
  }

  //上传封面
  const pickImage = (pos: string) => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头 
      success: function (res) {
        setCoverFileUrl(res)
        console.log(res, '选中的图片');
        uploadFile(res.tempFilePaths[0],
          (resUrl: string) => {
            //Fixme， 上传完成之前，都不允许点击保存按钮，否则请求后端的图片参数为空
            setPicUrl(resUrl);
          }
        )
      }
    })
  }

  //删除封面
  const handleDelImg = () => {
    setPicUrl("");
  }

  //删除暖场视频
  const deleteVideo = () => {
    setCoverFile("");
  }

  //上传暖场视频
  const pickVideo = (pos: string) => {
    // Taro.chooseVideo({
    Taro.chooseMedia({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {
        console.log('res的结果：', res)
        const tempFiles = res.tempFiles[0]
        const fileUrl = tempFiles.thumbTempFilePath; // 暖场视频封面
        const uploader = vodUploader({ mediaFile: tempFiles, coverFile: coverFileUrl },
          // const uploader = vodUploader({ mediaFile: res, coverFile: coverFileUrl },
          uploadRes => {
            console.log("结果", uploadRes);
            setPreLoadVideo(uploadRes.videoUrl);
            setCoverFile(fileUrl)
          },
          err => console.error("返回结果", err)
        )
        setVideoUploader(uploader);
      }
    })
  }

  //上传过场视频
  // const pauseVideo = (pos: string) => {
  //   Taro.chooseVideo({
  //     sourceType: ['album', 'camera'],
  //     maxDuration: 60,
  //     camera: 'back',
  //     success: function (res) {
  //       console.log(res.tempFilePath, 'res的结果')
  //       const fileUrl = picUrl;
  //       const uploader = vodUploader({ mediaFile: res, coverFile: coverFileUrl },
  //         uploadRes => {
  //           console.log("结果", uploadRes);
  //           setPreLoadVideo(uploadRes.videoUrl);
  //           setPauseFile(fileUrl)
  //         },
  //         err => console.error("返回结果", err)
  //       )
  //       setVideoUploader(uploader);
  //     }
  //   })
  // }
  //把按钮点击事件转化为observable
  const editLive$ = emitter.asObservable()
    .pipe(
      //防抖动(防重复)
      debounceTime(500),
      map(obj => obj as EditRoomParams),
      //接收按钮点击的参数
      switchMap(editLiveObj => {
        //roomId为空则是新创建直播
        if (!roomId) {
          if (!editLiveObj.roomName) {
            throw Taro.showToast({
              title: '请输入直播间名称',
              icon: 'none',
              duration: 2000
            })
          }
          if (!editLiveObj.description) {
            throw Taro.showToast({
              title: '请输入简介',
              icon: 'none',
              duration: 2000
            })
          }
          if (!editLiveObj.startTime) {
            throw Taro.showToast({
              title: '请输入开始时间',
              icon: 'none',
              duration: 2000
            })
          }
          if (!editLiveObj.endTime) {
            throw Taro.showToast({
              title: '请输入结束时间',
              icon: 'none',
              duration: 2000
            })
          }
          if (!editLiveObj.type) {
            throw Taro.showToast({
              title: '请选择直播方式',
              icon: 'none',
              duration: 2000
            })
          }
          if (!editLiveObj.direction) {
            throw Taro.showToast({
              title: '请选择观看方式',
              icon: 'none',
              duration: 2000
            })
          }
          if (!editLiveObj.picUrl) {
            throw Taro.showToast({
              title: '请选择直播间封面',
              icon: 'none',
              duration: 2000
            })
          }
          // 认证
          // firstValueFrom(authFacade.getapproveStatus());

          return roomFacade.createRoom(editLiveObj)
        } else {
          editLiveObj.roomId = roomId;
          //比较后得到新参数对象，只提交修改过的对象
          const submitParams = getObjDiff(oldParams.current, editLiveObj);

          console.log("submitParams:", submitParams)

          submitParams.roomId = roomId;
          if (isObjEmpty(submitParams)) return EMPTY;

          return roomFacade.editRoom(submitParams);
        }
      })
    )

  //FIXME 这里有执行两次的问题，是Taro的bug。等同于Component的componentWillMount
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<any>(
        editLive$
          .pipe(
            catchError(err => {
              //异常时恢复emitter以便可以重新触发点击
              setEmitter(initSubject);
              if (isPromise(err)) {
                return EMPTY;
              }
              // //点击直播时就应该判断是否认证
              else if (userApprovalStatus !== APPROVE_STATUS.SUCCESS && userApprovalStatus === APPROVE_STATUS.NEVER) { //实名认证提醒弹窗，并重定向到认证页面
                console.log('目前的个人认证状态1', userApprovalStatus);
                Taro.showToast({
                  title: "实名认证通过才能创建直播",
                  icon: 'none',
                  duration: 2000
                })
                setTimeout(() => {
                  Taro.redirectTo({
                    // url: '/pages/my/userVerify/index'
                    url: '/subPages/my/userVerify/index'
                  })
                }, 2000)
                return EMPTY;
              }
              else if (userApprovalStatus !== APPROVE_STATUS.SUCCESS && userApprovalStatus === APPROVE_STATUS.PENDING) { //实名认证提醒弹窗，并重定向到认证页面
                console.log('目前的个人认证状态2', userApprovalStatus);
                Taro.showToast({
                  title: "实名认证通过才能创建直播",
                  icon: 'none',
                  duration: 2000
                })
                setTimeout(() => {
                  Taro.redirectTo({
                    // url: '/pages/my/editInfo/index'
                    url: '/subpages/my/editInfo/index'
                  })
                }, 2000)
                return EMPTY;
              }
              else if (err.message.indexOf("系统错误") > -1) {
                Taro.showToast({
                  title: "系统错误，请稍后重试",
                  icon: 'none',
                  duration: 2000
                })
                return EMPTY;
              } else {
                throw err;
              }
            }),
            switchMap(newRoomId => {
              return roomFacade.saveRoomStat(newRoomId, ROOMSTATS_TYPE.CREATED)
                .pipe(
                  tap(() => {
                    Taro.showToast({
                      title: '创建成功',
                      icon: 'none',
                      duration: 2000
                    })

                    Taro.redirectTo({
                      url: `/pages/liveRoom/LiveDetails/index?roomId=${newRoomId}`
                    })
                  })
                )
            })
          ),
        () => console.log('创建时间：', startTime, endTime),
        err => {
          //异常时恢复emitter以便可以重新触发点击
          setEmitter(initSubject);
          logger.ERROR("保存信息失败！", err);
        }
      ),
    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter, userApprovalStatus]);

  //如果是从直播间跳转过来编辑直播间，则渲染已有数据
  useEffect(() => {
    if (roomId) {
      const room = roomFacade.getRoomInfo();
      setRoomName(room.roomName);
      setDescription(room.description)
      setPicUrl(room.picUrl)
      setPreLoadVideo(room.preLoadVideo)
      setPauseFile(room.pauseVideo)
      //BUG 页面方向显示有bug
      setWatch(room.direction)
      setStartTime(room.startTime.getTime())
      setEndTime(room.endTime.getTime())
      setIsEdit(true)

      const params = {
        roomId,
        roomName: room.roomName,
        description: room.description,
        picUrl: room.picUrl,
        type: room.type,
        preLoadVideo: room.preLoadVideo,
        pauseVideo: room.pauseVideo,
        direction: room.direction,
        startTime: room.startTime,
        endTime: room.endTime,
      }

      //传入完整旧参数对象
      oldParams.current = params;
    }
  }, [roomId])

  useEffect(() => {
    // console.log('当前的认证', userApprovalStatus);
  }, [userApprovalStatus])

  useDidShow(() => {
    // 获取认证状态
    firstValueFrom(authFacade.getapproveStatus());
  })

  return (
    <View className='index'>
      <View className='main'>
        <AtList>
          <AtListItem title='直播信息' className='title' />
        </AtList>
        <AtForm>
          <AtInput
            name='value1'
            title='直播标题'
            type='text'
            placeholder='编辑直播标题'
            value={roomName}
            onChange={handleChange1.bind(this)}
            className='text'
          >
            <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            <View className='icon'>*</View>
          </AtInput>
          {/* <AtInput
            name='value2'
            title='主持人'
            type='text'
            placeholder='用户名'
            value={ownerName}
            onChange={handleChange2.bind(this)}
            className='text'
          >
            <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
          </AtInput>
          <AtList hasBorder={false}>
            <AtListItem title='机构名称' className='title2' extraText='详细信息' arrow='right' />
          </AtList> */}
        </AtForm>
        <DateTimePicker onOk={pickStart} wrap-class='my-class' select-item-class='mySelector' title='开始时间' placeholder={formatTime(new Date(startTime))} />
        <View className='border'></View>
        <DateTimePicker onOk={pickEnd} wrap-class='my-class' select-item-class='mySelector' title='结束时间' placeholder={formatTime(new Date(endTime))} />
        <View className='describe'>
          <View>简介</View>
          <View className='icon1'>*</View>
        </View>
        <AtTextarea
          className='content'
          placeholder='这里编辑直播简介……'
          maxLength={500}
          value={description}
          onChange={handleChange4.bind(this)}
        />
        {/* <View className='title3'>服务选择</View>
        <AtRadio
          options={[
            { label: '试用版', value: true, desc: '仅支持简单的功能，在有限的观看人数进行直播试用。' },
            { label: '旗舰版', value: false, desc: '能使用所有功能，支持极高的观看人数进行影视级直播。' }
          ]}
          value={serve}
          onClick={handleChangeServe.bind(this)}
        > 
        </AtRadio>  */}
        <View className='title3'>直播方式</View>
        <AtRadio
          options={[
            { label: '手机直播', value: 0, desc: '使用手机作为直播工具进行直播。' },
            { label: '影视级直播', value: 1, disabled: true, desc: '能进行多机位切换，多音、视频源介入的专业直播，需由我们提供专业解决方案。联系我们。' }
          ]}
          value={select}
          onClick={handleChange5.bind(this)}
        />
        <View className='title3'>观看方式</View>
        <AtRadio
          options={[
            { label: '横屏观看', value: false, disabled: true, desc: '用户使用手机横屏观看直播。' },
            { label: '竖屏观看', value: true, desc: '用户使用手机竖屏观看直播。' }
          ]}
          value={watch}
          onClick={handleChange6.bind(this)}
        />
        <View className='title3'> 封面设置</View>
        <View className='border'></View>
        <View className='title1'>
          <Text className='push'>上传封面</Text>
        </View>
        <View className='check-img'>
          <Image src={picUrl} className='pick' onClick={() => pickImage("")}></Image>
          <View className='icon-del' onClick={handleDelImg} style={{ display: picUrl.length > 0 ? "block" : "none" }}>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/trash.png' className='iconDel_img'></Image>
          </View>
          <View className='check-img-title' style={{ display: picUrl.length > 0 ? "none" : "block" }}>建议尺寸16:9，不超过1MB</View>
        </View>
        <View className='border'></View>
        <View className='title1'>
          <Text className='push'>使用暖场视频</Text>
        </View>
        <View className='pickVideo'>
          <Image src={coverFile} className='pick1' onClick={() => pickVideo("")}></Image>
          <View className='iconDelVideo' onClick={deleteVideo} style={{ display: coverFile.length > 0 ? "block" : "none" }}>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/trash.png' className='delVideo_img'></Image>
          </View>
          <View className='size' style={{ display: coverFile.length > 0 ? "none" : "block" }}>建议尺寸16:9，不超过200MB</View>
          <View className='play' style={{ display: coverFile.length > 0 ? "block" : "none" }}>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
          </View>
        </View>
        {/* <View className='border'></View>
        <View className='title3'> 过场设置</View>
        <View className='border'></View>
        <View className='title1'>
          <Text className='push'>上传过场视频</Text>
        </View>
        <View className='pickPauseVideo'>
          <Image src={pauseFile} className='pick2' onClick={() => pauseVideo("")}></Image>
          <View className='size' style={{ display: pauseFile.length > 0 ? "none" : "block" }} >建议尺寸16:9，不超过200MB</View>
          <View className='play' style={{ display: pauseFile.length > 0 ? "block" : "none" }}>
            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
          </View>
        </View> */}
      </View>
      <View className='bt' onClick={() => emitter.next({
        roomName,
        picUrl,
        description,
        type: 2,
        direction: watch,
        startTime: new Date(startTime),
        endTime: new Date(endTime),
        preLoadVideo,
        pauseVideo: pauseFile,
      })}
      >
        <Text>{isEdit ? '确认修改' : '创建直播'}</Text>
      </View>
    </View >
  )
}
export default EditLive